import React, { Component } from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';
import { useTva } from 'tva';

import { handleApi } from '@packages/lib-api';
import os from '@packages/lib-os';

import FixedBottom from 'components/FixedBottom';
import AppGuidanceBanner from 'modules/appGuidanceBanner';
import { getPublishCategoryTip } from 'modules/PublishCategoryTip';
import uploadImage from 'modules/uploadImg';

import apiConfig from '../apiConfig';
import appBridge from '../wptBridge/oldVersion/appBridge';

import { updateMenuMsgStore } from './menuMsgStore';

import './Menu.less';

import showHide from '@wpt/showHide';

const API = handleApi({
    find: '/v1.0/remind/new-num-point',
    getWarehouseOrderRedPoint: '/v1.0/warehouseuser/get-entry-info-l',
    getIdentTips: '/v1.0/ident/tips-l', // 鉴真阁小红点
    getMainCategory: '/v1.0/my/get-main-category-l', // 获取商家主营分类
});

const IMAPI = handleApi(
    { getBottomMsgNum: '/v1.0/notice/bottom-msg-num' },
    {
        hostname: apiConfig.IM,
        namespace: 'msg',
        useEnv: true,
    }
);

const showPageNoAnimation = (url) => {
    if (url) {
        if (Date.now() / 1000 - WPT.loginTime > 43200) {
            WPT.redirect(url);
        } else {
            WPT.showPageNoAnimation(url);
        }
    }
};

// 回到顶部
function backToTop() {
    $(window).scrollTop(0);
}

// 获取背景图片
function getBgd(url) {
    return url ? { backgroundImage: `url(${url})` } : {};
}

// 我的
// 新增点击我的强制要求登录并绑定手机号
const handelmy = (isSeller, isBeanFirst) => async () => {
    let url = '/my/index/buyer?r=menu_my';

    if (!WPT.os.dyXcx && !WPT.os.bdXcx && (isSeller == 1 || localStorage.getItem('mineCenter') === 'seller')) {
        url = '/my/index/seller?r=menu_my';
    }

    if (WPT.userinfo && WPT.userinfo.isChildLogin) {
        url = '/scope/my?r=menu_my';
        WPT.showPage(url);
        return;
    }

    if (isBeanFirst) {
        localStorage.setItem('clickedMy', 1);
    }

    //如果不是APP&&不是百度xcx才执行下面逻辑
    if (!WPT.os.wpt && !WPT.os.bdXcx) {
        // 1、根据uri来判断用户是否登录，不知道是否会有问题
        if (!WPT.userinfo.userinfoUri) {
            await new Promise((resolve) => {
                WPT.login({
                    success: resolve,
                });
            });
        }
        // 2、当用户没有绑定手机号时进行绑定
        if (!WPT.userinfo.hasTelephone) {
            await new Promise((resolve) => {
                WPT.handleUserTelephone({ callback: resolve });
            });
        }
    }

    showPageNoAnimation(url);
};

const handelIndex = (item, isSelected) => () => {
    item.handleClick(item);

    if (isSelected) {
        backToTop();
        return;
    }

    let url = item.link;
    if (WPT.userinfo && WPT.userinfo.isChildLogin) {
        url = `/shop/${WPT.userinfo.userinfoUri}?r=menu_home`;
    }
    showPageNoAnimation(url);
};

const publish = () => {
    uploadImage(
        (serverIds, localIds, fileInfos) => {
            const wptServerIds = [];
            const wptLocalIds = [];
            for (let i = 0; i < serverIds.length; i++) {
                try {
                    wptLocalIds.push(localIds[i]);
                    localStorage.setItem('wpt_localIds', JSON.stringify(localIds));
                    wptServerIds.push(serverIds[i]);
                    localStorage.setItem('wpt_serverIds', JSON.stringify(serverIds));
                } catch (e) {
                    if (e.name === 'QuotaExceededError') {
                        WPT.Modal.loading('上传图片过大<br>请分批上传', {
                            time: 1000,
                            callback: () => {
                                WPT.showPage('/webApp/auction/saleEdit');
                            },
                        });
                    }
                    return;
                }
            }

            if (fileInfos && fileInfos.length > 0) {
                sessionStorage.setItem('yzl-fileInfos', JSON.stringify(fileInfos));
            }

            WPT.showPage('/webApp/auction/saleEdit');
        },
        {
            imgLimit: 9,
            openRemote: true,
            addMD5: true,
            getQr: true,
        }
    );
};

export const checkPublish = () => {
    // 对App进行特殊处理
    if (WPT.os.wpt && !((WPT.os.version >= '3.9.2' && WPT.os.ios) || (WPT.os.version >= '3.9.3' && WPT.os.android))) {
        const [, version = ''] = navigator.userAgent.match(/wptMessenger\/(\d+\.\d\.\d)/i) || [];
        const V = +version.replace(/\./g, '');
        // 153版本之后，App发拍原生化
        if (V == 170 && $.os.ios) {
            appBridge.jump(
                `${window.location.host}/webApp/auction/saleEdit154`,
                (result) => {
                    if (result == '0') {
                        publish();
                    }
                },
                { r: WPT.Util.getQueryString('r'), sc: WPT.getCookie('wptSceneChannel') }
            );
            return;
        }
        if (V >= 164) {
            appBridge.jump(
                `${window.location.host}/app/uploadImg/saleEdit`,
                (result) => {
                    if (result == '0') {
                        publish();
                    }
                },
                { r: WPT.Util.getQueryString('r'), sc: WPT.getCookie('wptSceneChannel') }
            );
            return;
        }
    }
    publish();
};

// TODO: 联系卖家
const touchSeller = (item) => () => {
    item.handleClick(item);

    WPT.scanRedirect(item.link, () => {
        WPT.showPage(item.link);
    });
};

const RemindConfig = {
    // "my","find","message","newRecommendNum  广告"
    '/webApp/discovery': ['newRecommendNum', 'app_top_banner'],
    '/uri/:uri@[0-9].*': ['message'],
    '/uri/:uri@A.*': ['message'],
    '/uri/:uri@N.*': ['message'],
    '/attention': ['message', 'newRecommendNum', 'app_top_banner'],
    '/': ['message', 'newRecommendNum', 'app_top_banner'],
    '/recommend': ['newRecommendNum', 'app_top_banner'],
    '/my/index/buyer': ['top_of_buy_new'], // 新版资源配置接口
    '/my/index/seller': ['top_of_sell'],
    '/my': ['top_of_sell', 'top_of_buy_new'], // 新版资源配置接口
    '/category': ['channel_top_banner_new'],
    '/residue/payResult/:type/:orderNo': ['pay_result_resource'], // 支付结果页
    '/webApp/payCombineOrder/result': ['pay_result_resource'], // 支付结果页
    '/live/payResult': ['pay_result_resource'], // 支付结果页
    '/webApp/payOrder/result': ['pay_result_resource'], // 支付结果页
    '/webApp/pay/pay_result/:out_trade_no': ['pay_result_resource'], // 老货款支付收银台专用
};

const AllowAppGuideConfig = [
    '/uri/:uri@[0-9].*',
    '/attention',
    '/webApp/discovery',
    '/recommend',
    '/my',
    '/my/index/buyer',
    '/home',
    '/handpickGoods',

    // 首页
    '/discovery',
    // 天天抽奖详情页
    '/raise/uri/:uri@R.*',
    // 拍品详情
    '/uri/:uri@A.*',
    '/uri/:uri@N.*',
];

// im消息红点数
function getNum({ bottom_message_num: bottomMessage }) {
    if (!bottomMessage) {
        return 0;
    }

    if (WPT.userinfo.expiredTime > WPT.nowTime) {
        return bottomMessage.msgNum;
    }
    return bottomMessage.buyerNum;
}

function IMNum() {
    const globalMenuStore = useTva('globalMenuStore');
    const num = getNum(globalMenuStore);

    return (
        num > 0 && (
            <div className={cx('numPoint', num > 99 && 'short', WPT.os.android && 'android')}>
                {num > 99 ? '99+' : num}
            </div>
        )
    );
}

let defaultRedPoint = '';

@showHide
export default class Menu extends Component {
    static propTypes = {
        // 向下滑动时是否隐藏menu, default false
        scrollHide: PropTypes.bool,
        // menu列表, example: ['首页', '发布', '消息', '我的', { name: 'custom', link: 'customLink' }]
        menus: PropTypes.arrayOf(
            PropTypes.oneOfType([
                PropTypes.string,
                PropTypes.shape({
                    name: PropTypes.string.isRequired,
                    link: PropTypes.string.isRequired,
                }),
            ])
        ).isRequired,
        // 当前高亮的菜单, 索引值. default null
        current: PropTypes.number,
        // 图标文字排列方式, vertical | horizontal
        theme: PropTypes.string,
        isSeller: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
        notice: PropTypes.object,
        isVerify: PropTypes.bool,
        holderHeight: PropTypes.string, // 底部撑开高度
        menuZIndex: PropTypes.number,
        identCallback: PropTypes.func, // 实物鉴定回调
    };

    static defaultProps = {
        scrollHide: false,
        current: null,
        theme: 'vertical',
        notice: null,
        isSeller: 0,
        isVerify: false,
        holderHeight: '0px',
        menuZIndex: '',
    };

    isHide = !!WPT.Util.query().hideBottomMenu;

    get menus() {
        return this.getMenus();
    }

    get config() {
        const isChildLogin = WPT.userinfo && WPT.userinfo.isChildLogin;

        const config = {
            首页: {
                className: 'myHome',
                fontClass: 'https://cdn.weipaitang.com/static/20190410695f5db1-cd86-4f68-a5dc-a5bfa413717a-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/2019041007968ab1-a122-4cd0-90ba-348a15ceaccc-W72H72',
                link: isChildLogin ? `/shop/${WPT.userinfo.userinfoUri}` : '/home?r=menu_home',
            },
            我的: {
                className: 'my',
                fontClass: 'https://cdn.weipaitang.com/static/2019041038295c4b-7835-4770-bd0c-ff18da83ece9-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/20190410b3477a68-ec54-4da4-9145-efc95225bf91-W72H72',
                link: isChildLogin ? '/scope/my' : '/my?r=menu_my',
            },
            分类: {
                className: 'category',
                fontClass: 'https://cdn.weipaitang.com/static/20190410b12a6cec-ef3b-4747-acea-2a1eb4562ca7-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/2019041081825c62-e43f-419e-8779-0a3054a4e863-W72H72',
                link: '/category?r=menu_category',
            },
            发布: {
                className: 'publish',
                fontClass: 'https://cdn.weipaitang.com/static/20190416ebad2672-54a8-4345-a494-c6ffb6427fd9-W72H72',
                link: '/webApp/auction/saleEdit',
            },
            直播: {
                className: 'live',
                fontClass: 'https://cdn.weipaitang.com/static/201904166af79ed6-f922-4d98-b025-3864d6f2fa75-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/2020032548761065-7674-10657674-db41-506e6e237766-W72H72',
                link: '/live/channel?r=menu_live',
            },
            卖家中心: {
                className: 'my',
                fontClass: 'https://cdn.weipaitang.com/static/2019041038295c4b-7835-4770-bd0c-ff18da83ece9-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/20190410b3477a68-ec54-4da4-9145-efc95225bf91-W72H72',
                link: isChildLogin ? '/scope/my' : '/my/index/seller',
            },
            进店逛逛: {
                className: 'enterShop',
                fontClass: 'https://cdn.weipaitang.com/static/2019041062f95c34-097b-453e-9c84-7533dad721c7-W72H72',
                link: `/shop/${WPT.userinfo.userinfoUri}`,
            },
            店铺: {
                className: 'enterShop',
                fontClass: 'https://cdn.weipaitang.com/static/201904168604ea81-85db-45c8-ac4e-65c4f48e76de-W72H72',
                link: `/shop/${WPT.userinfo.userinfoUri}`,
            },
            产品库管理: {
                className: 'productLib',
                fontClass: 'https://cdn.weipaitang.com/static/2019041110083de3-db5f-4b3b-87a6-a03727ea65cd-W64H64',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/2019041109e67f85-2783-436c-9d41-9509d6a9fa89-W128H128',
                link: '/webApp/productLib/mine',
                name: '管理',
            },
            产品库上拍: {
                className: 'productLibPublish',
                fontClass: 'https://cdn.weipaitang.com/static/20190410b7cfceed-0d21-44f9-96d1-0ed65799dd50-W64H64',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/201904112ee21ba5-1521-47ad-9d7d-45ee5a098559-W128H128',
                link: '/webApp/productLib/list',
                name: '上拍',
            },
            联系卖家: {
                className: 'contactSeller',
                fontClass: 'https://cdn.weipaitang.com/static/201904169856ecfc-1f7a-49bd-94f7-2acd15aaff54-W72H72',
                link: `/webApp/im/buyerChat?shopId=${WPT.userinfo.userinfoUri}&r=shop_menu_messages`,
            },
            足迹: {
                className: 'trace',
                fontClass: 'https://cdn.weipaitang.com/static/20190410d4426ac7-ea03-449c-bd00-d06d099df6d2-W64H64',
                link: '/webApp/my/traces?from=goods',
            },
            消息: {
                className: 'im',
                fontClass: 'https://cdn.weipaitang.com/static/20190410eda5e30f-6c2c-4a5d-9c9c-ce9878e04fbf-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/201904107ca51ca3-caf5-41f6-a6dd-1061d8fcdd56-W72H72',
                link: '/webApp/im/callCenter?r=menu_message',
            },
            云仓小程序好货: {
                className: 'miniProgramWarehouseWelfare',
                fontClass: 'https://cdn.weipaitang.com/static/2019111273c73fe2-0ede-3fe20ede-6499-61bc5c0dc33b-W96H96',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/201911125557591b-b964-591bb964-a977-8aba1705b123-W96H96',
                name: '好货',
                key: '云仓小程序好货',
            },
            云仓小程序个人页面: {
                className: 'miniProgramWarehouseWelfare',
                fontClass: 'https://cdn.weipaitang.com/static/2019082858dc3c5a-6b58-4bbb-9fa0-1987a99327e2-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/2019082896892925-d323-4520-a375-bf3ccee48fb5-W72H72',
                name: '云仓',
                key: '云仓小程序个人页面',
            },
            云仓集市: {
                className: 'warehouseCollection',
                fontClass: 'https://cdn.weipaitang.com/static/20190911f439da53-2718-49a8-8d4d-cfc472b199b3-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/201909119a5a844c-a854-47f7-98e1-764b1bc76cbb-W72H72',
                link: '/cloudWarehouse/market',
                name: '集市',
                key: '云仓集市',
            },
            云仓福利: {
                className: 'miniProgramWarehouseWelfare',
                fontClass: 'https://cdn.weipaitang.com/static/2020042910f06ca2-88fa-6ca288fa-ff60-6837ca6ecbab-W69H69',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/2020042961bff549-6150-f5496150-b75e-996420dbf544-W69H69',
                link: '/cloudWarehouse/welfare',
                name: '福利',
                key: '云仓福利',
            },
            云仓好货: {
                className: 'warehouseIndex',
                fontClass: 'https://cdn.weipaitang.com/static/2019111273c73fe2-0ede-3fe20ede-6499-61bc5c0dc33b-W96H96',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/201911125557591b-b964-591bb964-a977-8aba1705b123-W96H96',
                link: '/cloudWarehouse/goodStuff',
                name: '好货',
                key: '云仓好货',
            },
            云仓订单: {
                className: 'warehouseOrder',
                fontClass: 'https://cdn.weipaitang.com/static/2019082858dc3c5a-6b58-4bbb-9fa0-1987a99327e2-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/2019082896892925-d323-4520-a375-bf3ccee48fb5-W72H72',
                link: '/cloudWarehouse/myOrder',
                name: '云仓',
                key: '云仓订单',
            },
            鉴真阁首页: {
                className: 'ident',
                fontClass: 'https://cdn.weipaitang.com/static/201911013edc539f-15cc-48e5-8a84-4a2cc781dad4-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/20191101d9431a86-4ffb-4c57-b5b0-c3735ed77144-W72H72',
                link: '/ident',
                name: '首页',
                key: '鉴真阁首页',
            },
            鉴真阁我的鉴定: {
                className: 'identList',
                fontClass: 'https://cdn.weipaitang.com/static/20191101203023e9-bbba-48f1-a4f3-a5f03e374a01-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/20191101226125c9-2587-4b9e-8ab7-418180be6117-W72H72',
                link: '/ident/identList',
                name: '我的',
                key: '鉴真阁我的鉴定',
            },
            鉴真阁我的证书: {
                className: 'identList',
                fontClass: 'https://cdn.weipaitang.com/static/20191101cc3ad2c3-8d58-42e7-8ef0-2fd0551e952b-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/201911017712472a-9fa3-4a07-aa6d-6c3cf2755b40-W72H72',
                link: '/ident/identList',
                name: '我的鉴定',
                key: '鉴真阁我的证书',
            },
            鉴真阁实物鉴定: {
                className: 'toIdent',
                fontClass:
                    'https://cdn.weipaitang.com/static/20200706833d27e3-db0a-27e3db0a-19cd-e9630b0c22e2-W162H162',
                // https://cdn.weipaitang.com/static/202007061a1a2d64-f1b1-2d64f1b1-0bb1-36e8ad790c81-W108H108',
                name: WPT.os.wpt ? '鉴定' : '实物鉴定',
                key: '鉴真阁实物鉴定',
            },
        };

        // 微拍堂-鉴宝版马甲包
        if (WPT.os.wjb) {
            config['发布'] = config['分类'];
            Object.assign(config['发布'], { name: '分类' });
            Object.assign(config['首页'], {
                fontClass: 'https://cdn.weipaitang.com/static/201912196655e8c5-9a37-e8c59a37-997b-4f6979fc529f-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/201912197df89042-72d0-904272d0-e7f2-9ff91b378d0a-W72H72',
                name: '商城',
                link: '/home?r=menu_home',
            });
            Object.assign(config['直播'], {
                fontClass: 'https://cdn.weipaitang.com/static/2019122451e19ca7-b1ff-9ca7b1ff-e294-2aaaf179e885-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/20191224b54dea3b-06a8-ea3b06a8-441c-d9536282715a-W72H72',
            });
            config['鉴宝版首页'] = {
                className: 'myHome',
                fontClass: 'https://cdn.weipaitang.com/static/201912241c20e23c-4666-e23c4666-1b68-0dfe5ac99abf-W72H72',
                selectFontClass:
                    'https://cdn.weipaitang.com/static/201912242c84db5b-9d69-db5b9d69-770b-7da1a765f8b6-W72H72',
                link: '/community/home',
                name: '鉴宝',
            };
        }

        return config;
    }

    constructor(p) {
        super(p);
        this.state = {
            redPoint: defaultRedPoint,
            isSeller: 0,
            isBeanFirst: false,
            warehouseOrderRedPoint: {},
            identRedPoint: {},
            showPublishTips: '',
        };
    }

    componentDidMount() {
        this.getInit();
    }

    onPageShow = () => {
        this.getInit();
    };

    getInit = () => {
        const types = ['my', 'find', 'gate'].concat(RemindConfig[WPT.curRouter] || []);
        const menuNames = [];

        this.menus.forEach((item) => {
            if (item.name) {
                menuNames.push(item.name);
            } else {
                menuNames.push(item);
            }
        });

        if (menuNames.includes('消息') || this.menus[2]) {
            types.push('bottom_message_num');
        }

        if (this.props.menus.includes('云仓订单')) {
            this.getWarehouseOrderRedPoint();
        }

        if (this.props.menus.includes('鉴真阁我的鉴定')) {
            this.getIdentTips();
        }

        if (this.props.menus.includes('发布')) {
            this.getMainCategories();
        }

        WPT.getData(API.find, { type: types.join(',') }, (res) => {
            const data = res.data || {};
            const redPoint = data.type;
            // 作为缓存，短时间内来讲redPoint是稳定的
            defaultRedPoint = redPoint;

            this.setState(
                {
                    redPoint,
                    isSeller: data.isSeller,
                    isBeanFirst: data.isBeanFirst,
                },
                () => {
                    const { type, ...item } = data;
                    WPT.msgData = item;
                    WPT.$curPage.trigger('menu-msg', [item]);
                    // 此接口bottom_message_num已废弃，使用IMAPI接口返回数据
                    const { bottom_message_num: _, ...noBottomMessage } = item;
                    updateMenuMsgStore(noBottomMessage);
                }
            );
        });

        // 底部红点
        WPT.getData(IMAPI.getBottomMsgNum, ({ code, data = {} }) => {
            if (code == 0) {
                updateMenuMsgStore(data);
                this.setState({
                    isVerify: data.bottom_message_num ? data.bottom_message_num.isVerify : false,
                });
            }
        });

        setTimeout(() => {
            const instance = WPT[`Page-${WPT.$curPage.data('page')}`];
            if (instance) {
                instance.menu = this;
            }
        });
        WPT.loginCallback = () => {
            this.getInit();
        };
    };

    getMenus() {
        let menus = this.props.menus.slice();

        if (os.wpt && WPT.os.version < '2.7.0' && !WPT.os.wjb) {
            return menus;
        }
        const menuStr = menus.join(',');

        if (WPT.os.wjb) {
            if (menuStr === '首页,分类,消息,我的' || menuStr === '首页,发布,消息,我的') {
                return ['鉴宝版首页', '直播', '首页', '我的'];
            }
        }

        menus = menus.map((item) => {
            if (item == '发现' || item.name == '发现') {
                return '消息';
            }
            return item;
        });

        return menus;
    }

    getWarehouseOrderRedPoint() {
        if (!WPT.userinfo.userinfoUri) {
            return;
        }
        WPT.getData(API.getWarehouseOrderRedPoint, { type: 1 }, (res) => {
            res.code == 0 && this.setState({ warehouseOrderRedPoint: res.data.redPoint });
        });
    }

    getIdentTips() {
        WPT.getData(API.getIdentTips, { type: 1 }, (res) => {
            res.code == 0 && this.setState({ identRedPoint: res.data });
        });
    }

    getMainCategories() {
        WPT.os.wpt &&
            WPT.getData(API.getMainCategory, (res = {}) => {
                if (res.code !== 0) {
                    return;
                }
                const { mainCategory, mainSecCategory } = res.data || {};
                this.setState({ showPublishTips: getPublishCategoryTip(mainCategory, mainSecCategory) });
            });
    }

    getItemText(item = {}) {
        if (item.activityIcon) {
            return '';
        }
        if (item.icon119) {
            return '';
        }
        return item.name;
    }

    handleClick = (item, isSelected) => {
        const { isBeanFirst, isVerify } = this.state;
        let { isSeller } = this.state;
        if (WPT.curRouter == '/webApp/my/sellerSettings') {
            isSeller = this.props.isSeller;
        }

        if (item.key === '云仓福利') {
            return showPageNoAnimation(item.link);
        }
        if (item.key === '云仓小程序好货') {
            return wx.miniProgram.redirectTo({ url: '/pages/cloudNiceGoods/index' });
        }
        if (item.key === '云仓小程序个人页面') {
            return wx.miniProgram.redirectTo({ url: '/pages/warehouse/index' });
        }

        if (item.onClick) {
            return item.onClick;
        }
        if (item.name === '发布') {
            return checkPublish;
        }
        if (item.name === '联系卖家') {
            return touchSeller(item);
        }
        if (item.name === '我的' && item.className === 'my') {
            return handelmy(isSeller, isBeanFirst);
        }
        if (item.name === '首页' && item.className === 'myHome') {
            return handelIndex(item, isSelected);
        }
        if (['分类'].includes(item.name)) {
            return () => {
                showPageNoAnimation(item.link);
            };
        }
        if (item.name === '进店逛逛') {
            return () => {
                showPageNoAnimation(item.link);
            };
        }

        if (item.name == '消息') {
            return () => {
                let { link } = item;
                // 卖家中心点击消息，提醒气泡消失，2019-06-14 开始 7天有效期
                if (this.props.isSeller) {
                    WPT.localStorage.setItem('sellerMessageTip', 'close');
                }
                // 底部menu切换 app内不要传递type
                if (os.wpt && os.wptAppVerison >= 270) {
                    link = WPT.Util.urlAddQuery(link, { nav: 'im' });
                } else {
                    link = WPT.Util.urlAddQuery(link, { nav: 'im', type: isVerify ? 'staff' : 'user' });
                }
                showPageNoAnimation(link);
            };
        }

        if (item.name == '店铺') {
            return () => undefined;
        }

        if (item.key == '云仓订单') {
            const { purchaseCount, saleCount } = this.state.warehouseOrderRedPoint;
            const tab = !purchaseCount && saleCount ? '2' : '1';
            item.link = WPT.Util.urlAddQuery(item.link, { tab });
            return () => {
                showPageNoAnimation(item.link);
            };
        }

        if (item.key == '鉴真阁我的证书') {
            return () => {
                const url = WPT.Util.urlAddQuery('/pages/certificate/home/index', {
                    fr: WPT.Util.getQueryString('fr'),
                });
                if (window.wx.miniProgram) {
                    window.wx.miniProgram.redirectTo({ url });
                } else {
                    WPT.Modal.tips('请在鉴真阁小程序中查看');
                }
            };
        }

        return () => {
            showPageNoAnimation(item.link);
        };
    };

    getStyle(item, hasShop) {
        if (hasShop && !['进店逛逛', '联系卖家'].includes(item.name)) {
            const style = {};
            if (item.activityIcon) {
                style.backgroundImage = `url(${item.activityIcon})`;
            }
            return style;
        }

        return {};
    }

    handleTipsClose = (e) => {
        e.stopPropagation();
        this.setState({
            showPublishTips: '',
        });
        WPT.localStorage.setItem('hidePublishTips', true);
    };

    identClick = (e) => {
        e && e.preventDefault();
        e.stopPropagation();
        // if (!WPT.os.wpt) {
        //     return;
        // }
        const { identCallback } = this.props;
        identCallback && identCallback();
    };

    render() {
        // 如果是有匠App，不显示menu
        if (this.isHide || os.yjPlatform || ['standard', 'ident'].includes(WPT.Util.getQueryString('fr'))) {
            return null;
        }

        // 子账户的话 替换底部菜单按钮链接
        const { notice: Notice, menuZIndex, current } = this.props;
        // 有没有包含店铺
        const hasShop = this.menus.some((item) => ['进店逛逛', '联系卖家'].includes(item.name || item));
        const { config } = this;
        const menus = this.menus.map((menu) => {
            const name = menu.name || menu;
            const configItem = {
                ...config[name],
                handleClick: menu.onClick || (() => {}),
            };
            configItem.name = configItem.name || name;
            if (menu.name && menu.link) {
                configItem.link = menu.link;
            }

            return configItem;
        });
        const showAppGuideBanner = WPT.matchByPathname(window.location.pathname, AllowAppGuideConfig);
        const { warehouseOrderRedPoint, identRedPoint } = this.state;
        return (
            <FixedBottom
                style={{ zIndex: menuZIndex || 99 }}
                holderHeight={this.props.holderHeight}
                scrollHide={this.props.scrollHide}
            >
                {showAppGuideBanner && <AppGuidanceBanner />}
                <div
                    ref={(c) => {
                        this.dom = c;
                    }}
                    className={cx(
                        'mainMenu-modules',
                        this.props.theme,
                        (menus.length === 3 || menus.length === 2) && 'slotFlex'
                    )}
                >
                    {Notice && <Notice />}
                    {menus.map((item, i) => {
                        const isSeleted = current === i;
                        if (item.key == '鉴真阁实物鉴定') {
                            return (
                                <div className="toIdent" onClick={this.identClick}>
                                    <div className="identIcon" style={getBgd(item.fontClass)} />
                                    <div className="identText">{this.getItemText(item)}</div>
                                </div>
                            );
                        }
                        return (
                            <a
                                style={this.getStyle(item, hasShop)}
                                key={item.name}
                                className={cx('menuItem', item.className, {
                                    last: i === 3,
                                    selected: isSeleted,
                                    hasShop,
                                })}
                                {...WPT.onTouchEnd(() => {
                                    const fn = this.handleClick(item, isSeleted);
                                    $.isFunction(fn) && fn();
                                })}
                            >
                                {item.icon119 ? (
                                    <div
                                        className="icon119"
                                        style={getBgd(isSeleted ? item.selectIcon119 : item.icon119)}
                                    />
                                ) : (
                                    <>
                                        <div className="icon">
                                            <div
                                                style={
                                                    item.activityIcon
                                                        ? { display: 'none' }
                                                        : getBgd(
                                                              isSeleted
                                                                  ? item.selectFontClass || item.fontClass
                                                                  : item.fontClass
                                                          )
                                                }
                                                className="iconImg"
                                            />
                                        </div>
                                        <div className={cx('text', isSeleted && 'active')}>
                                            <span>{this.getItemText(item)}</span>
                                        </div>
                                    </>
                                )}
                                {this.state.redPoint === item.className && <div className="redPoint" />}
                                {item.name == '消息' && <IMNum />}
                                {item.key == '云仓订单' && warehouseOrderRedPoint.totalCount > 0 && (
                                    <div
                                        className={cx(
                                            'numPoint',
                                            warehouseOrderRedPoint.totalCount > 99 && 'short',
                                            WPT.os.android && 'android'
                                        )}
                                    >
                                        {warehouseOrderRedPoint.totalCount > 99
                                            ? '99+'
                                            : warehouseOrderRedPoint.totalCount}
                                    </div>
                                )}
                                {item.key == '鉴真阁我的鉴定' && identRedPoint.identFirstNum > 0 && (
                                    <div
                                        className={cx(
                                            'numPoint',
                                            identRedPoint.identFirstNum > 99 && 'short',
                                            WPT.os.android && 'android'
                                        )}
                                    >
                                        {identRedPoint.identFirstNum > 99 ? '99+' : identRedPoint.identFirstNum}
                                    </div>
                                )}
                            </a>
                        );
                    })}
                    {this.state.showPublishTips && !WPT.localStorage.getItem('hidePublishTips') && (
                        <div className="publish-tips" {...WPT.onTouchEnd(this.handleTipsClose)}>
                            <i className="close wptFM icon-fm-addicon" />
                            <span>{this.state.showPublishTips}</span>
                            <span className="arrow" />
                        </div>
                    )}
                </div>
            </FixedBottom>
        );
    }
}
